/** @type {HTMLCanvasElement} */

const canvas = document.getElementById("canvas");
if (canvas.getContext) {
  let ctx = canvas.getContext("2d");

  let ball = {
    x: 100,
    y: 100,
    vx: 1,
    vy: 10,
    radius: 25,
    color: "blue",
    draw: function () {
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
      ctx.fillStyle = this.color;
      ctx.fill();
    },
  };

  function draw() {
    if (Math.floor(ball.vy) === 0 && Math.floor(ball.y + ball.radius) === canvas.height) return;
    //每次绘制前清除画布
    ctx.fillStyle = "rgba(255, 255, 255, 0.3)";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ball.draw();

    //触碰边界改变方向
    if (ball.x + ball.radius + ball.vx > canvas.width || ball.x - ball.radius + ball.vx < 0) {
      ball.vx = -ball.vx;
    }
    if (ball.y + ball.radius + ball.vy > canvas.height || ball.y - ball.radius + ball.vy < 0) {
      ball.vy = -ball.vy;
    }
    //添加加速度
    ball.vy *= 0.99;
    ball.vy += 0.15;

    ball.x += ball.vx;
    ball.y += ball.vy;
    window.requestAnimationFrame(draw);
  }

  window.requestAnimationFrame(draw);
}
